package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/factory")
public class FactoryController extends BaseController {

    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list", name = "厂家列表查询")
    public String list(
            @RequestParam(defaultValue = "1", name = "page") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.setOrderByClause("create_time desc");
        PageInfo pageInfo = factoryService.findByPage(pageNum, pageSize,factoryExample);

        request.setAttribute("page", pageInfo);
        return "/cargo/factory/factory-list";
    }


    @RequestMapping(value = "/toAdd", name = "跳转厂家新增页面")
    public String toAdd() {
        return "/cargo/factory/factory-add";
    }


    //新增和修改统一用一个方法处理
    @RequestMapping(value = "/edit", name = "厂家新增")
    public String edit(Factory factory) {
        if (StringUtils.isEmpty(factory.getId())) {
            //1. 设置主键
            factory.setId(UUID.randomUUID().toString());

            factory.setCreateTime(new Date());
            factory.setUpdateTime(new Date());

            factoryService.save(factory);
        } else {
            factory.setUpdateTime(new Date());
            factoryService.update(factory);
        }
        //重定向到list方法
        return "redirect:/cargo/factory/list.do?Id=" + factory.getId();
    }



    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        //根据id查询工厂信息
        Factory factory = factoryService.findById(id);
        request.setAttribute("factory",factory);
        return "cargo/factory/factory-update";
    }




    @RequestMapping(value = "/delete", name = "厂家删除")
    public String delete(String id) {
        //调用service删除
        factoryService.delete(id);

        //重定向到list方法
        return "redirect:/cargo/factory/list.do";
    }

    public String setFactoryIdByUUid() {
        return UUID.randomUUID().toString().substring(0, 4);
    }


}
